package com.medical.client.controller.unit;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.medical.client.controller.RootController;
import com.medical.client.controller.utils.HttpUtils;
import com.medical.client.controller.utils.LoadingUtils;
import com.medical.client.model.Context;
import com.medical.client.model.UnitTable;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;

/**
 * @ClassName: BorderController
 * @Description: TODO
 * @Author: JackyLee
 * @Date: 2024/5/28 22:34
 **/
public class BorderController extends RootController {

    @FXML
    private TableView<UnitTable> tableView;

    @FXML
    private TableColumn<UnitTable, String> unitno;

    @FXML
    private TableColumn<UnitTable, String> unitname;

    @FXML
    private TableColumn<UnitTable, Boolean> selectedColumn;

    @FXML
    private TextArea ta;

    private ObservableList<UnitTable> items;

    @FXML
    private CheckBox allCheck;

    @FXML
    protected void allSelect() {
        if (allCheck.isSelected()) {
            items.forEach(item -> item.setSelectedProperty(true));
        } else {
            items.forEach(item -> item.setSelectedProperty(false));
        }
    }


    @FXML
    private void initialize() {
        unitno.setCellValueFactory(new PropertyValueFactory<>("unitno"));
        unitname.setCellValueFactory(new PropertyValueFactory<>("unitname"));
        selectedColumn.setCellValueFactory(cellData -> cellData.getValue().selectedProperty());
        selectedColumn.setCellFactory(CheckBoxTableCell.forTableColumn(selectedColumn));

        //初始化表格和监听事件
        items = FXCollections.observableArrayList();
        //list添加值对象
        tableView.setItems(items); //tableview添加list
        tableView.setEditable(true);

        // 添加监听器以响应复选框的变化
        selectedColumn.setCellFactory(tc -> {
            CheckBoxTableCell<UnitTable, Boolean> cell = new CheckBoxTableCell<>();
            cell.setSelectedStateCallback(index -> {
                if (index >= 0 && index < items.size()) {
                    System.out.println(items.get(index).getUnitname()+"=="+items.get(index).selectedProperty());
                    return items.get(index).selectedProperty();
                } else {
                    System.out.println("yyyyy");
                    return new SimpleBooleanProperty(false);
                }
            });
            return cell;
        });
    }

    public void setData(String unitName) {

        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.show();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(true);
            tableView.setDisable(true);
            tableView.getItems().clear();
        });

        boolean isCheck = Context.checkBox.get("unit")!=null?Context.checkBox.get("unit"):false;
        try {
            String result = HttpUtils.sendGetRequest("http://127.0.0.1:9009/api/wh/external/query/unit?unitName="+unitName+"&isCheck"+isCheck);
            JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();

            if(jsonResult!=null){
                if(jsonResult.get("data")!=null){
                    JsonArray jsonArray = jsonResult.getAsJsonArray("data");
                    for (int i=0;i<jsonArray.size();i++){
                        JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
                        UnitTable unitTable = new UnitTable();
                        unitTable.setUnitname(jsonObject.get("unitname").getAsString());
                        unitTable.setUnitno(jsonObject.get("unitno").getAsString());
                        items.add(unitTable);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.close();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(false);
            tableView.setDisable(false);
        });
    }

    public void uploadData(){
        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.show();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(true);
            tableView.setDisable(true);
            tableView.getItems().clear();
        });

        try {
            // 遍历items，获取选中的数据，并上传到服务器
            StringBuffer stringBuffer = new StringBuffer();
            items.forEach(item->{
                if(item.selectedProperty().getValue()){

                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("unitname",item.getUnitname());
                    jsonObject.addProperty("unitno",item.getUnitno());

                    ta.setText(jsonObject.toString());
                    String result = HttpUtils.sendPostRequest("http://127.0.0.1:9009/api/wh/external/units",jsonObject.toString());

                    JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();
                    String data = jsonResult.get("data").getAsString();
                    stringBuffer.append(data);
                    stringBuffer.append("\n");
                    ta.setText(stringBuffer.toString());
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.close();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(false);
            tableView.setDisable(false);
        });
    }

    public void clearData(){
        Platform.runLater(() -> {
            // 更新UI的代码
            LoadingUtils.close();
            GridController functionController = (GridController) Context.controllers.get("com.medical.client.controller.unit.GridController");
            functionController.setBtu(false);
            tableView.setDisable(false);
        });

        tableView.getItems().clear();
        ta.clear();
    }

    @FXML
    public void onRowClick(MouseEvent mouseEvent) {
        if (mouseEvent.getClickCount() == 2) {
            if(tableView.getSelectionModel().getSelectedItem()!=null){
                UnitTable unitTable = tableView.getSelectionModel().getSelectedItem();

                String result = HttpUtils.sendGetRequest("http://127.0.0.1:9009/api/wh/external/queryUnitNo?unitNo="+unitTable.getUnitno());

                JsonObject jsonResult = JsonParser.parseString(result).getAsJsonObject();
                String data = jsonResult.get("data").getAsString();

                ta.setText(data);
            }
        }else {
            ta.setText("单击");
        }
    }
}
